package bank;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class _02TwoAdd {
    public static ListNode02 addTwoNumbers(ListNode02 l1, ListNode02 l2) {
        ListNode02 listNode = new ListNode02(0);
        long intL1=0,intL2=0;
        ListNode02 p1 = l1,p2=l2,p=listNode;
        double index = 0;
        while (p1 != null){
            intL1 = (long) (intL1+p1.val*Math.pow(10,index));
            index ++;
            p1 = p1.next;
        }
        index = 0;
        while (p2 != null){
            intL2 = (long) (intL2+p2.val*Math.pow(10,index));
            index ++;
            p2 = p2.next;
        }

        //这里有个问题，int类型的数据取值范围有限，所以算不出值很大的数据
        int result = (int)(intL1 + intL2);
        while(true){
            p.val = result%10;
            result /= 10;
            if(result == 0){
                break;
            }
            p.next = new ListNode02();
            p = p.next;
        }

        return listNode;
    }

    //这里参考一个正确算法
    //避免了大整数的叠加
    /*public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode cursor = root;
        int carry = 0;
        while(l1 != null || l2 != null || carry != 0) {
            int l1Val = l1 != null ? l1.val : 0;
            int l2Val = l2 != null ? l2.val : 0;
            int sumVal = l1Val + l2Val + carry;

            //carry表示进位，当sumVal>10的时候carry=1
            carry = sumVal / 10;

            ListNode sumNode = new ListNode(sumVal % 10);
            cursor.next = sumNode;
            cursor = sumNode;

            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }

        return root.next;
    }*/

    private static class ListNode02 {
        int val;
        ListNode02 next;

        ListNode02() {
        }

        ListNode02(int val) {
            this.val = val;
        }

        ListNode02(int val, ListNode02 next) {
            this.val = val;
            this.next = next;
        }
    }
}
